package com.thesis.client;

import java.io.File;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewConfiguration;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;


import com.thesis.conectify.Connectify;
import com.thesis.internet.InternetManager;
import com.thesis.object.ListDishes;
import com.thesis.utils.Defines;
import com.thesis.utils.Utils;

public class LoginActivity extends Activity {
//	 SharedPreferences prefs = getSharedPreferences("MyPref", MODE_PRIVATE);
//	    SharedPreferences.Editor prefEdit = prefs.edit();
	
	SharedPreferences settings; 
	private int responseCode = 0;
	ProgressDialog pDialog;
	ProgressDialog dDialog;
	EditText login_username;
	EditText login_password;
	TextView login_error;
	int[] result;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		 settings = getSharedPreferences(Defines.PREFS_NAME, 0);
		setAlwaysShowActionOverflow(this);
		if (!InternetManager.sharedInstance().isInternetConnected(this)) {
			Utils.sharedInstance().showShortToast(
					LoginActivity.this,
					getResources().getString(
							R.string.dialog_internet_message_short));
		}
	
		login_username = (EditText) findViewById(R.id.login_username);
		login_password = (EditText) findViewById(R.id.login_password);
		login_username.setText("manager");
		login_password.setText("manager");
		Button btn_login = (Button) findViewById(R.id.btn_login);
		btn_login.setBackground(getResources().getDrawable(
				R.drawable.button_login));
		login_error = (TextView) findViewById(R.id.login_error);
		CheckBox cb_show_pass = (CheckBox) findViewById(R.id.login_show_password);
		
		cb_show_pass.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				// TODO Auto-generated method stub
				if (!isChecked) {
					login_password
							.setTransformationMethod(PasswordTransformationMethod
									.getInstance());
					
				} else {
					login_password
							.setTransformationMethod(HideReturnsTransformationMethod
									.getInstance());
				}
			}
		});

		btn_login.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (!InternetManager.sharedInstance().isInternetConnected(
						LoginActivity.this)) {

					Utils.sharedInstance().showShortToast(
							LoginActivity.this,
							getResources().getString(
									R.string.dialog_internet_message_short));
				}
				else {
					new LoginTask().execute();
				}

			}

		});

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.login, menu);
		return super.onCreateOptionsMenu(menu);
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {
		
		case R.id.action_changeip:
			AlertDialog.Builder editalert = new AlertDialog.Builder(this);

			editalert.setTitle("Đổi IP server");
			//editalert.setMessage("here is the message");

			SharedPreferences.Editor editor = settings.edit();
			final EditText input = new EditText(this);
			input.setText(settings.getString("ipServer", "0.0.0.0"));
			LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
			        LinearLayout.LayoutParams.FILL_PARENT,
			        LinearLayout.LayoutParams.FILL_PARENT);
			input.setLayoutParams(lp);
			editalert.setView(input);

			editalert.setPositiveButton("Xác nhận", new DialogInterface.OnClickListener() {
			    public void onClick(DialogInterface dialog, int whichButton) {
			    	
			         SharedPreferences.Editor editor = settings.edit();
			         editor.putString("ipServer", input.getText().toString());
			         editor.commit();
			         dialog.dismiss();

			    }
			});
			editalert.setNegativeButton("Hủy", new DialogInterface.OnClickListener() {
			    public void onClick(DialogInterface dialog, int whichButton) {
			    	
			    	dialog.dismiss();
			    }
			});


			editalert.show();
			
			 return true;
		default:
			return super.onOptionsItemSelected(item);
		}

	}
	public void setAlwaysShowActionOverflow(Context context) {
		try {
			ViewConfiguration config = ViewConfiguration.get(context);
			java.lang.reflect.Field menuKeyField = ViewConfiguration.class
					.getDeclaredField("sHasPermanentMenuKey");
			if (menuKeyField != null) {
				menuKeyField.setAccessible(true);
				menuKeyField.setBoolean(config, false);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	class LoginTask extends AsyncTask<String, Void, Integer> {

		@Override
		protected void onPreExecute() {
			pDialog = new ProgressDialog(LoginActivity.this);
			pDialog.setMessage(getResources().getString(R.string.process_login));
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		@Override
		protected Integer doInBackground(String... param) {
			// TODO Auto-generated method stub
			// check for login respond
			String username = login_username.getText().toString();
			String password = login_password.getText().toString();
			
			Connectify connect = new Connectify(LoginActivity.this);
			result = connect.login(username, password);
			connect.getAllDishType();

			if (result[0] != 9 && result[0] != 8) {
				responseCode = 1;

			} else {
				responseCode = 0;
			}
			
			if (responseCode == 1){
				
				File file = new File("/sdcard/restautant/");
				if(file.exists())     {
					
					Utils.sharedInstance().parseJsonDish(settings.getString("data_dish", "{}"));
				} 
				else {
					
					connect.getAllDishestoDatabase();
					connect.downloadUserImage();
					connect.downloadDishImage();
					connect.downloadTableImage();
					Utils.sharedInstance().unpackZip("/sdcard/restautant/", "user.zip");
					Utils.sharedInstance().unpackZip("/sdcard/restautant/", "dish.zip");
					Utils.sharedInstance().unpackZip("/sdcard/restautant/", "table.zip");
					//Utils.sharedInstance().parseJsonDish(settings.getString("data_dish", "{}"));
					
					
				}
			}

			return responseCode;
		}

		@Override
		protected void onPostExecute(Integer responseCode) {
			pDialog.dismiss();
			
			if (responseCode == 1) {
			
				Intent intent = new Intent(LoginActivity.this,
						TableMapActivity.class);
				intent.putExtra(Defines.USER_LOGIN_ROLE, result);

				startActivity(intent);

				// startActivity(new
				// Intent(LoginActivity.this,MenuActivity.class));
			} else {
				if (result[0] == 9){
					login_error.setText(getResources().getString(
							R.string.login_err_false));
				}  else {
					Utils.sharedInstance().showShortToast(LoginActivity.this, "Vui long check ip server");
				}
				
			}
		}
	}
}
